package com.egg.auth.service.login.factory;

import cn.dev33.satoken.stp.StpUtil;
import com.egg.auth.entity.user.UserAccount;
import com.egg.auth.enums.account.AccountStateEnum;
import com.egg.auth.enums.account.AccountTypeEnum;
import com.egg.auth.enums.account.DeviceTypeEnum;
import com.egg.auth.model.LoginUserInfo;
import com.egg.auth.model.request.Login;
import com.egg.auth.service.login.ILoginFactory;
import com.egg.auth.service.login.LoginHelper;
import com.egg.auth.service.user.IUserAccountService;
import com.egg.auth.utils.PasswordUtil;
import com.egg.basic.fegin.BasicCaptchaFeignClient;
import com.egg.common.core.exception.CustomException;
import com.egg.common.core.model.response.ResponseData;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;

/**
 * @author east
 */
@Service
public class LoginFactoryPassword implements ILoginFactory, InitializingBean {


    @Autowired
    private BasicCaptchaFeignClient basicCaptchaFeignClient;
    @Autowired
    private IUserAccountService userAccountService;


    @Override
    public void afterPropertiesSet() {
        container.put(AccountTypeEnum.PASSWORD.getCode(), this);
    }

    @Override
    public ResponseData<String> login(Login login) {
        ResponseData<Boolean> rd = basicCaptchaFeignClient.captchaImageVerifyGet(
                login.getLoginCaptchaId(), login.getLoginCaptchaCode()
        );
        if (rd.isSuccess() && !rd.getData()) {
            return ResponseData.error("验证码错误");
        }

        Optional<UserAccount> opt = userAccountService.findByUsername(AccountTypeEnum.PASSWORD.getCode(), login.getUsername());
        if (!opt.isPresent() || !PasswordUtil.equalsPassword(login.getPassword(), opt.get().getPassword())) {
            throw new CustomException("账号或密码错误");
        }
        if (!Objects.equals(AccountStateEnum.ENABLED.getCode(), opt.get().getState())) {
            throw new CustomException("账号非启用状态");
        }
        LoginUserInfo loginUserInfo = LoginHelper.buildLoginUser(AccountTypeEnum.PASSWORD, opt.get().getUserId());
        LoginHelper.login(loginUserInfo, DeviceTypeEnum.get(login.getDeviceType()));
        return ResponseData.success(StpUtil.getTokenValue());
    }


}
